--
-- Author: ping.wang
-- Date: 2019-04-30 16:15:32
--
-- NewRankView
--

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)
local TabsBtn = require("app.widget.TabsBtn")
local ListMenu = require("app.widget.ListMenu")
local NewRankFirstTargetRender = import(".renders.NewRankFirstTargetRender")
local NewRankSecondTargetRender = import(".renders.NewRankSecondTargetRender")
local NewGuildRankRender = import(".renders.NewGuildRankRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

ClassRef.VIEW_ROOT_RES = Res.NewRankScene

function ClassRef:init()
    self._ui.Button_back:addClickEventListener(function()
        self:closeView()
    end)


    local btns = {}
    for i = 1,2 do
        btns[i] = self._ui.Panel_tab:getChildByName("selected_btn_"..i)
    end

    local function onTabsBtn(index, btn)
        --self:_refreshViewByIndex(index)
        if index == 1 then
            --此处关掉这个界面打开角色的排行榜界面 先这么着
            executeFunc(self._onCloseView)
            UIHandler:handleMessage({id = Constant.FUNC_TYPE_RANK, mode = "open"})
        end
    end

    self._tabsBtn = TabsBtn.new(btns, onTabsBtn, 2)

    self._tipsBtn = self._ui.Panel_top_1:findChild("btn_tips")
    self._tipsBtn:addClickEventListener(
        function()
            local posTemp = self._tipsBtn:convertToWorldSpace(cc.p(0,0))
            local width, height = self._tipsBtn:getContentSize2()
            posTemp.x = posTemp.x + width
            self:showTips(posTemp)
        end
    )

    self:refreshTopTitle()
    --左侧listmenu相关
    local function operate(op, data)
        if op == "btnClick" then
            self._guildRankList:selectBtn( data.id, 1 )
        elseif op == "subBtnClick" then
            self._selectedIdx = data.id
            self._selectedRankConfig = data.rankConfig
            executeFunc(self._onOperate, "showRankInfo", data.rankConfig)
        end
    end
    local params = {
        list = self._ui["Panel/ListView"],
        btnClass = NewRankFirstTargetRender,
        subBtnClass = NewRankSecondTargetRender,
        operate = operate,
        mustHaveTarget = true,
        onlyOpen = true,
        autoHideSecond = true,
    }
    self._guildRankList = ListMenu.new(params)


    self:setMyGuildRankText("")
    --底部的分页按钮
    self._curShowPageIdx = 1
    self._maxPageNum = 1
    self._totalRankNum = 0
    self._leftPageBtn = self._ui.Panel_page:findChild("Button_1")
    self._rightPageBtn = self._ui.Panel_page:findChild("Button_2")

    self._leftPageBtn:addClickEventListener(function()
        --显示前一页
        if self._productListNode and self._curShowPageIdx > 1 then
            self._curShowPageIdx = self._curShowPageIdx - 1
            self._productListNode:jumpToIndex((self._curShowPageIdx - 1) * 20 + 1)
            self._ui.Panel_page:findChild("num"):setString(string.format("%d/%d",self._curShowPageIdx ,self._maxPageNum))
        end
    end)

    self._rightPageBtn:addClickEventListener(function()
        --显示下一页
        self._ui.Panel_r:findChild("ScrollView_1"):stopAllActions()
        if self._productListNode and self._curShowPageIdx < self._maxPageNum then
            self._curShowPageIdx = self._curShowPageIdx + 1
            self._productListNode:jumpToIndex((self._curShowPageIdx - 1) * 20 + 1)
            self._ui.Panel_page:findChild("num"):setString(string.format("%d/%d",self._curShowPageIdx ,self._maxPageNum))
        end
    end)


    self._myGuildPaiming = 0 --初始化设置我的公会排名
    --底部左侧放大镜按钮
    self._ui.Panel_r:findChild("Button"):addClickEventListener(function()
        --显示下一页
        if UD:isInGuild() then
            --跳转到这一行
            if self._myGuildPaiming > 0 and self._myGuildPaiming <= 100 then
                self._productListNode:jumpToIndex(self._myGuildPaiming)
            else
                --提示应该是未上榜
                display.pushToast(L("tips_3000406"))
            end
        else
            display.pushToast(L("rankGuild4"))
        end
    end)


    --中间显示部分
    self._ui.Panel_r:findChild("ListView1"):setVisible(false)
    self._ui.Panel_r:findChild("ScrollView_1"):setVisible(true)
    self._ui.Panel_r:findChild("ScrollView_1").bounce = false
    self._scrollViewSize = self._ui.Panel_r:findChild("ScrollView_1"):getContentSize()


    local params = {
        renderClass = NewGuildRankRender,
        perNum = 1,
        cellEventProxy = function(eventName, data)
            executeFunc(self._onOperate, eventName, data)
        end,
        allEventListen = function(sender, eventType)
            --滚动事件监听 用来控制下面的翻页按钮 20条为一页最多五页
            if eventType == ccui.ScrollviewEventType.scrolling then -- 滚动中
                local curOffsetY = sender:getInnerContainer():getPositionY() - self._scrollViewSize.height

                local cellMode = self._productListNode:getCellModelByIndex(1)
                if cellMode then
                    local perHeight = cellMode.size.height
                    local tempIdx =  self._maxPageNum - math.ceil(math.ceil(-curOffsetY /perHeight)/20) + 1
                    if tempIdx <= 0 then
                        tempIdx = 1
                    elseif tempIdx > self._maxPageNum then
                        tempIdx = self._maxPageNum
                    end
                    self._curShowPageIdx = tempIdx
                    self._ui.Panel_page:findChild("num"):setString(string.format("%d/%d",self._curShowPageIdx ,self._maxPageNum))
                end
            elseif eventType == ccui.ScrollviewEventType.scrollToTop then
                self._curShowPageIdx = 1
                self._ui.Panel_page:findChild("num"):setString(string.format("%d/%d",self._curShowPageIdx ,self._maxPageNum))
            elseif eventType == ccui.ScrollviewEventType.scrollToBottom then
                self._curShowPageIdx = self._maxPageNum
                self._ui.Panel_page:findChild("num"):setString(string.format("%d/%d",self._curShowPageIdx ,self._maxPageNum))
            end
        end,
    }

    self._productListNode = ListViewVertical.new( self._ui.Panel_r:findChild("ScrollView_1"), params )
end

--初始化左侧rank列表 传入参数为rank数据和默认选择的rankid
--model读取配置而来的数据 table_insert(self._guildRankInfos, {rankConfig = v})
function ClassRef:initLeftList(menuData,selectedRankId)
   
    if self._guildRankList and menuData then
        self._guildRankList:removeAllMenus()
        local firstSelectIndex = 1
        local secondSelectIndex = 1
        if selectedRankId then
            local rankId = tonumber(selectedRankId)
            for k, v in pairs(menuData) do
                local isFind = false
                for k1, v1 in pairs(v.subDatas) do
                    if tonumber(v1.rankConfig.ID) == selectedRankId then
                        isFind = true
                        secondSelectIndex = k1
                    end
                end
                if isFind then
                    firstSelectIndex = v.id
                    break
                end
            end
        end
    
        self._guildRankList:refreshList(menuData)
        self._guildRankList:selectBtn(firstSelectIndex,secondSelectIndex,false)
    end
end

function ClassRef:getCName(aT)
    local ret = ""
    if aT == 1 then
        ret = L("lua_code_text_390")
    elseif aT == 2 then
        ret = L("lua_code_text_379")
    elseif aT == 3 then
        ret = L("lua_code_text_402")
    elseif aT == 4 then
        ret = L("lua_code_text_162")
    elseif aT == 5 then
        ret = L("lua_code_text_408")
    elseif aT == 6 then
        ret = L("rankSubtitle_6")
    elseif aT == 7 then
        ret = L("rankSubtitle_7")
    elseif aT == 8 then
        ret = L("rankSubtitle_8")
    elseif aT == 9 then
        ret = L("rankSubtitle_9")
    end

    return ret
end

function ClassRef:refreshTopTitle()
    if self._selectedRankConfig then
        --刷新title
        --Panel_top是四列 Panel_top 是三列 三列还是死列取决于rank的 Subtitle1和 Subtitle2列
        --公会排行不太一样 最好单独给一个title
        if checknumber(self._selectedRankConfig.Subtitle1) ~= 0 and checknumber(self._selectedRankConfig.Subtitle2) ~= 0 then
            --用四列
            local curTopTitle = self._ui.Panel_top
            self._ui.Panel_top:setVisible(true)
            self._ui.Panel_top_1:setVisible(false)
            self._ui.Panel_top_team:setVisible(false) --team暂时不考虑

            curTopTitle:findChild("name"):setString(L("bossRank_guildName"))
            curTopTitle:findChild("job"):setString(self:getCName(checknumber(self._selectedRankConfig.Subtitle1)))
            curTopTitle:findChild("combat"):setString(self:getCName(checknumber(self._selectedRankConfig.Subtitle2)))
            curTopTitle:findChild("time"):setString(L(self._selectedRankConfig.list))
        else
            --这里约定好三列肯定是填写supertitle1
            --用三列
            local curTopTitle = self._ui.Panel_top_1
            self._ui.Panel_top:setVisible(false)
            self._ui.Panel_top_1:setVisible(true)
            self._ui.Panel_top_team:setVisible(false)

            self._tipsBtn = curTopTitle:findChild("btn_tips")
            self._tipsBtn:addClickEventListener(
                function()
                    local posTemp = self._tipsBtn:convertToWorldSpace(cc.p(0,0))
                    local width, height = self._tipsBtn:getContentSize2()
                    posTemp.x = posTemp.x + width
                    self:showTips(posTemp)
                end
            )

            curTopTitle:findChild("name"):setString(L("bossRank_guildName"))
            curTopTitle:findChild("job"):setString(self:getCName(checknumber(self._selectedRankConfig.Subtitle1)))
            curTopTitle:findChild("time"):setString(L(self._selectedRankConfig.list))
        end
    end
end

function ClassRef:refreshView(data)
    self:refreshTopTitle()
    if self._tipsBtn then
        self._tipsBtn:setVisible(checknumber(self._selectedRankConfig.ID) == Enums.GuildRankType.TotalCombatPower 
                                        or checknumber(self._selectedRankConfig.ID) == Enums.GuildRankType.CSTotalCombatPower)
    end

    self._myGuildPaiming = 0
    if data and data.rankInfos and #data.rankInfos > 0 then
        self._productListNode:reloadData(data.rankInfos,{startIndex = 1})
        --刷新最大页数和当前页数
        self._totalRankNum = #data.rankInfos
        self._maxPageNum = math.ceil(self._totalRankNum/20)
        if  self._maxPageNum <= 0 then
            self._maxPageNum = 1
        -- elseif  self._maxPageNum > 5 then
        --     self._maxPageNum = 5
        end

        self._curShowPageIdx = 1

        self._ui.Panel_page:findChild("num"):setString(string.format("%d/%d",self._curShowPageIdx ,self._maxPageNum))
        self._ui.Panel_tips:setVisible(false)
        --再刷新我的排名 我的公会排名
        self._myGuildPaiming = data.myGuildPaiming
        if data.myGuildPaiming > 0 then
            local myGuildDisplayData = self:getGuildRankListContent()
            if myGuildDisplayData > 10000 then
                myGuildDisplayData = string.format("%d%s",math.floor(myGuildDisplayData/10000),L("damageunit1"))
            end

            self:setMyGuildRankText(string.format(L("rankGuild2"), myGuildDisplayData, data.myGuildPaiming))
        else
            if UD:isInGuild() then
                local myGuildDisplayData = self:getGuildRankListContent()
                if myGuildDisplayData > 10000 then
                    myGuildDisplayData = string.format("%d%s",math.floor(myGuildDisplayData/10000),L("damageunit1"))
                end

                self:setMyGuildRankText(string.format(L("rankGuild1"), myGuildDisplayData))
            else
                self:setMyGuildRankText(L("rankGuild3"))
            end
        end
    else
        --显示长颈鹿
        self._productListNode:reloadData({},{startIndex = 1})
        self._ui.Panel_tips:setVisible(true)
        self._curShowPageIdx = 1
        self._maxPageNum = 1
        self._ui.Panel_page:findChild("num"):setString(string.format("%d/%d",self._curShowPageIdx ,self._maxPageNum))

        --再刷新我的排名 我的公会排名
        --todo 之后改为我的公会数据 暂无数据
        --判断我是否有公会
        if UD:isInGuild() then
            self:setMyGuildRankText(string.format(L("rankGuild1"), 0))
        else
            self:setMyGuildRankText(L("rankGuild3"))
        end
    end
end

function ClassRef:setMyGuildRankText(str)
    local text = self._ui.Panel_r:findChild("text")
    text:setString(str)
    local textSize = text:getContentSize()
    local bg = self._ui.Panel_r:findChild("bg1")
    bg:setContentSize(cc.size(100 + textSize.width ,bg:getContentSize().height))
end

function ClassRef:showTips(posTemp)
    if not self._tips then
        self._tips = cc.CSLoader:createNode("ui2/strengthen/Node_jewel_tips.csb")
        display.nodeRemoveForNotHit(self._tips, function()
            if self._tips then
                self._tips:removeFromParent()
                self._tips = nil
            end
        end)
        local text = self._tips:findChild("Panel/text")
        text:setString(L("rankGuild6"))
        self._tips:setPosition(posTemp.x - 350,posTemp.y + 30)
        local size = self._tips:findChild("Panel"):getContentSize()


        text:getVirtualRenderer():setDimensions( 320, 0 )
        local textSize = text:getVirtualRendererSize()
        text:setContentSize(320,textSize.height)

        local lastSize = cc.size(size.width + 30,size.height + textSize.height - 82)

        self._tips:findChild("Panel"):setContentSize(lastSize)
        self._tips:setContentSize(lastSize)
        self._tips:findChild("Panel/bg"):setContentSize(lastSize)
        ccui.Helper:doLayout(self._tips)
        self._root:addChild(self._tips)
    end
end

--第三列 根据rankid来取
function ClassRef:getGuildRankListContent()
    local guildModel = app:getInst("NewguildModel")
    if not self._selectedRankConfig or not guildModel then
        return 0
    end

    local ginfo = guildModel:getMyGuildInfo()
    if not ginfo then
        return 0
    end

    local rankId = tonumber(self._selectedRankConfig.ID)

    if rankId == Enums.GuildRankType.GuildLv then
        return ginfo:getGuildLv()
    elseif rankId == Enums.GuildRankType.TotalCombatPower or rankId == Enums.GuildRankType.CSTotalCombatPower then
        return ginfo:getGuildTotalCombatPw()
    elseif rankId == Enums.GuildRankType.ActivityMemberNums then
        return ginfo:getActiveMemberNum()
    elseif rankId == Enums.GuildRankType.TotalContributions or rankId == Enums.GuildRankType.CSTotalContributions then
        return ginfo:getTotalContribution()
    elseif rankId == Enums.GuildRankType.TotalProsperity or rankId == Enums.GuildRankType.CSTotalProsperity then
        return ginfo:getTotalProsperity()
    end
    return 0
end

return ClassRef
